<?php

namespace services\wechat;

use common\components\Service;
use common\models\wechat\WechatTemplate;
use services\common\MessageService;
use Yii;

class WechatTemplateService extends Service
{
    /**
     * 获取新增客户订阅模板IDs
     * @return array
     */
    public static function getPatientSubTempalteIds(): array
    {
        return WechatTemplate::find()
            ->select(['template_id'])
            ->where([
                'type' => [WechatTemplate::TYPE_ADD_PATIENT, WechatTemplate::TYPE_MONTH_BILL, WechatTemplate::TYPE_INCOME_PAY],
                'status' => WechatTemplate::STATUS_ENABLE
            ])
            ->andWhere(['!=', 'template_id', ''])
            ->limit(3)
            ->column();
    }

    /**
     * @param int $type 模板类型  1 = 预约, 2 取消预约
     * @param array $content 模板内容 字段内容排序按照模板字段顺序  ['张三', '张医生', '2021', '合肥华研']
     */
    public static function sendTemplate(int $type, array $content, string $openid): void
    {
//        $openid = Yii::$app->user->identity->user->wx_mini_openid;
        if (empty($openid)) {
            return;
        }
        // 获取 模板id
        $wechatTemplate = WechatTemplate::findOne([
            'type' => $type,
            'status' => WechatTemplate::STATUS_ENABLE
        ]);
        if (empty($wechatTemplate)) {
            return;
        }
        // 参数
        $params = $wechatTemplate->params;
        $data = [];
        foreach ($params as $value) {
            $data[$value] = ['value' => $content[$value] ?? ''];
        }
        // 发送
        MessageService::sendWechat($wechatTemplate->template_id, $openid, $data);
    }
}